package com.zbkj.crmeb.chant.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.CommonPage;
import com.common.PageParamRequest;
import com.crmeb.core.common.CommonResult;
import com.crmeb.core.exception.CrmebException;
import com.crmeb.core.utils.TableNameUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.utils.PriceUtil;
import com.utils.ProductConvertUtil;
import com.zbkj.crmeb.chant.dao.ChannelPickingDao;
import com.zbkj.crmeb.chant.model.CategoryMatch;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.model.ChannelPicking;
import com.zbkj.crmeb.chant.request.PickingListRequest;
import com.zbkj.crmeb.chant.request.PickingProductsRequest;
import com.zbkj.crmeb.chant.request.SavePickingRequest;
import com.zbkj.crmeb.chant.response.PickingProductResponse;
import com.zbkj.crmeb.chant.service.ChannelPickingService;
import com.zbkj.crmeb.chant.service.ICategoryMatchService;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.merchant.api.response.AppletPickingProductResponse;
import com.zbkj.crmeb.merchant.api.response.FrontPickingResponse;
import com.zbkj.crmeb.merchant.api.service.MerStoreCartService;
import com.zbkj.crmeb.store.dao.StoreProductAttrValueDao;
import com.zbkj.crmeb.store.model.StoreCart;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.model.StoreProduct;
import com.zbkj.crmeb.store.model.StoreProductAttrValue;
import com.zbkj.crmeb.store.model.StoreProductMer;
import com.zbkj.crmeb.store.model.StoreProductPicking;
import com.zbkj.crmeb.store.model.Supplier;
import com.zbkj.crmeb.store.response.StoreCartResponse;
import com.zbkj.crmeb.store.response.StoreProductCartProductInfoResponse;
import com.zbkj.crmeb.store.service.StoreOrderService;
import com.zbkj.crmeb.store.service.StoreProductMerService;
import com.zbkj.crmeb.store.service.StoreProductPickingService;
import com.zbkj.crmeb.store.service.StoreProductService;
import com.zbkj.crmeb.store.service.SupplierService;
import com.zbkj.crmeb.user.service.UserService;

/**
 * <p>
 * 商户批采单表 服务实现类
 * </p>
 *
 * @author wuzp
 * @since 2022-05-19
 */
@Service
public class ChannelPickingServiceImpl extends ServiceImpl<ChannelPickingDao, ChannelPicking> implements ChannelPickingService {

    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private ICategoryMatchService categoryMatchService;
    @Autowired
    private SupplierService supplierService;
    @Resource
    private StoreProductAttrValueDao storeProductAttrValueDao;
    @Autowired
    private PriceUtil priceUtil;
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private MerStoreCartService storeCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private StoreProductMerService storeProductMerService;
    @Autowired
    private StoreProductPickingService storeProductPickingService;
    @Autowired
    private StoreOrderService storeOrderService;
    @Autowired
    private ProductConvertUtil productConvertUtil;

    @Override
    public PageInfo<ChannelPicking> getMerPickingList(PickingListRequest request, Integer merId) {
        checkPicking(merId);
        LambdaQueryWrapper<ChannelPicking> lambdaQueryWrapper = Wrappers.<ChannelPicking>lambdaQuery()
                .eq(ChannelPicking::getMerId, merId)
                .eq(ChannelPicking::getIsDel,0)
                .orderByDesc(ChannelPicking::getSort).orderByDesc(ChannelPicking::getId);
        if(request.getReceiptType() != null){
            lambdaQueryWrapper.eq(ChannelPicking::getReceiptType,request.getReceiptType());
        }
        if(StringUtils.isNotBlank(request.getSearch())){
            lambdaQueryWrapper.and(e->e.like(ChannelPicking::getId,request.getSearch()).or().like(ChannelPicking::getName,request.getSearch()));
        }
        Page<ChannelPicking> page = PageHelper.startPage(request.getPage(), request.getLimit());
        List<ChannelPicking> pickingList = this.list(lambdaQueryWrapper);
        return CommonPage.copyPageInfo(page, pickingList);
    }

    @Override
    public CommonResult<String> savePicking(SavePickingRequest request) {
        checkPicking(request.getMerId());
        ChannelPicking channelPicking = new ChannelPicking();
        BeanUtils.copyProperties(request,channelPicking);
        return this.saveOrUpdate(channelPicking) ? CommonResult.success() : CommonResult.failed();
    }

    @Override
    public CommonResult<String> deletePicking(Integer id, Integer merId) {
        checkPicking(merId);
        int count = storeOrderService.count(Wrappers.<StoreOrder>lambdaQuery().eq(StoreOrder::getPickingId, id));
        if(count > 0){
            throw new CrmebException("该批采单已存在订单");
        }
        //没有则删除
        boolean update = this.update(Wrappers.<ChannelPicking>lambdaUpdate().set(ChannelPicking::getIsDel, 1).eq(ChannelPicking::getId, id));
        return update ? CommonResult.success() : CommonResult.failed();
    }

    @Override
    public PageInfo<PickingProductResponse> getProducts(PickingProductsRequest request) {
        checkPicking(request.getMerId());
        //查询该批采单是否存在
        ChannelPicking picking = this.getById(request.getPickingId());
        if(picking == null || picking.getIsDel() == 1){
            throw new CrmebException("该批采单不存在");
        }
        getProductConfig(request);
        Page<StoreProduct> page = PageHelper.startPage(request.getPage(), request.getLimit());
        List<PickingProductResponse> list = storeProductAttrValueDao.selectPickingProduct(request);
        if(CollectionUtils.isEmpty(list)){
            return CommonPage.copyPageInfo(page, list);
        }
        productConvertUtil.convertProductPickingImage(list);
        //处理分类
        List<Integer> cateIds = list.stream().map(PickingProductResponse::getCateId).distinct().collect(Collectors.toList());
        //获取三连分类名称
        Map<Integer,String> cateMap = categoryMatchService.getTripletCateName(cateIds);
        // 批量查询子表
        List<Integer> ids = list.stream().map(PickingProductResponse::getProductId).distinct().collect(Collectors.toList());
        List<StoreProductMer> storeProductMers = storeProductMerService.list(Wrappers.<StoreProductMer>lambdaQuery()
                .in(StoreProductMer :: getProductId, ids)
        );
        Map<Integer, StoreProductMer> storeProductMerMap = storeProductMers.stream().collect(Collectors.toMap(StoreProductMer::getProductId, s -> s, (v1, v2) -> v1));
        //计算价格
        List<StoreProduct> productList = storeProductService.list(Wrappers.<StoreProduct>lambdaQuery().in(StoreProduct::getId, ids));
        Map<Integer, StoreProduct> productMap = productList.stream().collect(Collectors.toMap(StoreProduct::getId, e -> e));
        List<String> skuIdList = list.stream().map(PickingProductResponse::getSkuId).distinct().collect(Collectors.toList());
        List<StoreProductAttrValue> productAttrValueList = storeProductAttrValueDao.selectList(Wrappers.<StoreProductAttrValue>lambdaQuery()
                .in(StoreProductAttrValue::getSourceSkuId, skuIdList)
                .in(StoreProductAttrValue::getProductId,ids));
        Map<Integer, List<StoreProductAttrValue>> map = productAttrValueList.stream().collect(Collectors.groupingBy(StoreProductAttrValue::getProductId));
        List<StoreProductAttrValue> values = new ArrayList<>();
        for (Map.Entry<Integer, List<StoreProductAttrValue>> entry : map.entrySet()) {
            StoreProduct storeProduct = productMap.get(entry.getKey());
            if(storeProduct == null){
                continue;
            }
            //计算规格售价
            priceUtil.calcProductValuePrice(entry.getValue(), request.getMerId(),storeProduct,picking.getReceiptType(),storeProductMerMap,true, null,true,null);
            values.addAll(entry.getValue());
        }
        Map<String, StoreProductAttrValue> valueMap = values.stream().collect(Collectors.toMap(StoreProductAttrValue::getSourceSkuId, e -> e, (v1, v2) -> v1));
        for (PickingProductResponse response : list) {
            if(cateMap != null){
                response.setCateName(cateMap.get(response.getCateId()));
            }
            StoreProductAttrValue value = valueMap.get(response.getSkuId());
            if(value == null){
                continue;
            }
            response.setPrice(value.getPrice());
            response.setCost(value.getCost());
            response.setTaxAndSecondPrice(value.getTaxAndSecondPrice());
            response.setOtPrice(value.getOtPrice());
            StoreProduct storeProduct = productMap.get(value.getProductId());
            if(storeProduct != null){
                response.setSeasonCode(storeProduct.getSeasonCode());
                response.setColorCode(storeProduct.getColorCode());
            }
            //计算批发价
            if(response.getPriceType() == 0){
                response.setWholesalePrice(response.getCost().multiply(BigDecimal.ONE.add(response.getWholesalePrice().movePointLeft(2))).setScale(2, RoundingMode.UP).add(response.getTaxAndSecondPrice()));
            }
        }
        return CommonPage.copyPageInfo(page, list);
    }

    public static void main(String[] args) {
        BigDecimal bigDecimal = BigDecimal.ZERO.movePointLeft(2);
        System.out.println(bigDecimal);
    }

    @Override
    public List<ChannelPicking> getMerPickingDropList(Integer type, Integer merId) {
        checkPicking(merId);
        LambdaQueryWrapper<ChannelPicking> lambdaQueryWrapper = Wrappers.<ChannelPicking>lambdaQuery().eq(ChannelPicking::getIsDel, 0)
                .eq(ChannelPicking::getMerId, merId).orderByDesc(ChannelPicking::getSort).select(ChannelPicking::getId, ChannelPicking::getName);
        if(type == 1){
            lambdaQueryWrapper.gt(ChannelPicking::getStatementTime,new Date());
        }
        return this.list(lambdaQueryWrapper);
    }

    @Override
    public PageInfo<FrontPickingResponse> getPickingList(Integer merId, PageParamRequest pageParamRequest) {
        checkPicking(merId);
        //批采单
        Page<ChannelPicking> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<ChannelPicking> pickingList = this.list(Wrappers.<ChannelPicking>lambdaQuery().eq(ChannelPicking::getIsDel, 0)
                .eq(ChannelPicking::getMerId, merId)
                .gt(ChannelPicking::getStatementTime,new Date())
                .eq(ChannelPicking::getStatus,1)
                .orderByDesc(ChannelPicking::getSort));
        List<FrontPickingResponse> responseList = new ArrayList<>();
        if(CollectionUtils.isEmpty(pickingList)){
            return CommonPage.copyPageInfo(page, responseList);
        }
        ChannelMerchant channelMerchant = channelMerchantService.getChannelMerchantByMerId(merId);
        //可见配置
        List<Integer> brandIdsList= JSON.parseArray(channelMerchant.getBrandIds(), Integer.class);
        List<Integer> suppliersIdList = JSON.parseArray(channelMerchant.getSuppliersIds(), Integer.class);
        List<Integer> tempIdList = JSON.parseArray(channelMerchant.getTempId(), Integer.class);
        if (CollectionUtils.isNotEmpty(suppliersIdList)) {
            Supplier supplier = supplierService.getSupplierBarcode(merId);
            if (null != supplier) {
                suppliersIdList.add(supplier.getId());
            }
        }
        Integer userId = userService.getUserId();
        //不可见分类
        List<Integer> cateIdList = categoryMatchService.selectCategoryMatchDisable(merId).stream().map(CategoryMatch::getId).collect(Collectors.toList());
        for(ChannelPicking channelPicking : pickingList) {
            FrontPickingResponse response = new FrontPickingResponse();
            BeanUtils.copyProperties(channelPicking,response);
            //查询批采单部分商品 (上架有库存)
            LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = Wrappers.<StoreProduct>lambdaQuery()
                    .eq(StoreProduct::getIsShow,1).gt(StoreProduct::getStock,0);
            if(CollectionUtils.isNotEmpty(brandIdsList)){
                lambdaQueryWrapper.in(StoreProduct::getBrandId,brandIdsList);
            }
            if(CollectionUtils.isNotEmpty(suppliersIdList)){
                lambdaQueryWrapper.in(StoreProduct::getSuppliersId,suppliersIdList);
            }
            if(CollectionUtils.isNotEmpty(tempIdList)){
                lambdaQueryWrapper.in(StoreProduct::getTempId,tempIdList);
            }
            if(CollectionUtils.isNotEmpty(cateIdList)){
                lambdaQueryWrapper.notIn(StoreProduct::getCateId,cateIdList);
            }
            lambdaQueryWrapper.notInSql(StoreProduct::getId, "SELECT product_id FROM " + TableNameUtil.getProductMerName(merId) + " WHERE is_not_show = 1");
            lambdaQueryWrapper.inSql(StoreProduct::getId,"SELECT DISTINCT v.product_id FROM eb_store_product_picking p LEFT JOIN eb_store_product_attr_value v on p.sku_id = v.source_sku_id where v.stock > 0 and p.picking_id = " + channelPicking.getId());
//            lambdaQueryWrapper.inSql(StoreProduct::getId,"SELECT DISTINCT product_id FROM eb_store_product_picking where picking_id = " + channelPicking.getId());
            lambdaQueryWrapper.select(StoreProduct::getId,StoreProduct::getStoreName);
            lambdaQueryWrapper.last("LIMIT 4");
            List<StoreProduct> productList = storeProductService.list(lambdaQueryWrapper);
            productConvertUtil.convertProductImage(productList);
            response.setPartProductList(productList);
            if(userId > 0){
                StoreCart storeCart = storeCartService.getOne(Wrappers.<StoreCart>query().select("sum(cart_num) as cartNum ").lambda().eq(StoreCart::getIsNew, 0)
                        .eq(StoreCart::getPickingId, channelPicking.getId()).eq(StoreCart::getUid, userId));
                if(storeCart != null){
                    response.setSelectedQuantity(storeCart.getCartNum());
                }
            }
            if (Objects.nonNull(response.getMinimumType()) && response.getMinimumType() == 2) {
                response.setMinimumPrice(response.getMinimumPrice().setScale(2, RoundingMode.UP));
            }
            responseList.add(response);
        }
        
        List<FrontPickingResponse> list = responseList.stream().filter(e->CollectionUtils.isNotEmpty(e.getPartProductList())).sorted(Comparator.comparing(FrontPickingResponse::getSort).reversed()).collect(Collectors.toList());
        return CommonPage.copyPageInfo(page, list);
    }

    @Override
    public PageInfo<AppletPickingProductResponse> getPickingProducts(Integer pickingId, Integer merId, PageParamRequest pageParamRequest) {
        List<AppletPickingProductResponse> appletPickingProductResponses = new ArrayList<>();
        checkPicking(merId);
        //查询该批采单是否存在
        ChannelPicking picking = this.getById(pickingId);
        if(picking == null || picking.getIsDel() == 1){
            throw new CrmebException("该批采单不存在");
        }
        PickingProductsRequest request = new PickingProductsRequest();
        request.setMerId(merId);
        request.setPickingId(pickingId);
        getProductConfig(request);
        Page<StoreProduct> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        request.setIsApplet(1);
        List<PickingProductResponse> applitList = storeProductAttrValueDao.selectApplitPickingProduct(request);
        if(CollectionUtils.isEmpty(applitList)){
            return CommonPage.copyPageInfo(page, appletPickingProductResponses);
        }
        List<Integer> productIdList = applitList.stream().map(PickingProductResponse::getProductId).collect(Collectors.toList());
        //图片处理
        productConvertUtil.convertProductPickingImage(applitList);
        List<StoreProductPicking> productPickingList = storeProductPickingService.list(Wrappers.<StoreProductPicking>lambdaQuery().in(StoreProductPicking::getProductId, productIdList)
                .eq(StoreProductPicking::getPickingId, pickingId));
        Map<String, StoreProductPicking> pickingMap = productPickingList.stream().collect(Collectors.toMap(StoreProductPicking::getSkuId, e -> e, (v1, v2) -> v1));
        List<StoreProductAttrValue> valueList = storeProductAttrValueDao.selectList(Wrappers.<StoreProductAttrValue>lambdaQuery()
                .in(StoreProductAttrValue::getSourceSkuId, pickingMap.keySet())
                .in(StoreProductAttrValue::getProductId,productIdList)
                .gt(StoreProductAttrValue::getStock, 0));
        Map<Integer, List<StoreProductAttrValue>> valueMap = valueList.stream().collect(Collectors.groupingBy(StoreProductAttrValue::getProductId));
        List<PickingProductResponse> list = new ArrayList<>();
        for (PickingProductResponse response : applitList) {
            List<StoreProductAttrValue> attrValueList = valueMap.get(response.getProductId());
            for (StoreProductAttrValue value : attrValueList) {
                PickingProductResponse productResponse = new PickingProductResponse();
                BeanUtils.copyProperties(response,productResponse);
                productResponse.setSkuId(value.getSourceSkuId());
                productResponse.setPrice(value.getPrice());
                productResponse.setCost(value.getCost());
                productResponse.setStock(value.getStock());
                productResponse.setSuk(value.getSuk());
                StoreProductPicking storeProductPicking = pickingMap.get(value.getSourceSkuId());
                productResponse.setPriceType(storeProductPicking.getPriceType());
                productResponse.setWholesalePrice(storeProductPicking.getPrice());
                productResponse.setId(storeProductPicking.getId());
                list.add(productResponse);
            }
        }
//        List<PickingProductResponse> list = storeProductAttrValueDao.selectPickingProduct(request);
//        if(CollectionUtils.isEmpty(list)){
//            return CommonPage.copyPageInfo(page, list);
//        }
        //计算批采商品批发价
        priceUtil.calcPickingProductWholesalePrice(list,request.getMerId(),picking.getReceiptType());
        Map<Integer, List<PickingProductResponse>> listMap = list.stream().collect(Collectors.groupingBy(PickingProductResponse::getProductId));
        for (Map.Entry<Integer, List<PickingProductResponse>> entry : listMap.entrySet()) {
            List<PickingProductResponse> values = entry.getValue();
            PickingProductResponse productResponse = values.get(0);
            AppletPickingProductResponse response = new AppletPickingProductResponse();
            BeanUtils.copyProperties(productResponse,response);
            List<AppletPickingProductResponse.AppletPickingSku> skuList = new ArrayList<>();
            for (PickingProductResponse value : values) {
                AppletPickingProductResponse.AppletPickingSku sku = new AppletPickingProductResponse.AppletPickingSku();
                BeanUtils.copyProperties(value,sku);
                skuList.add(sku);
            }
            response.setSkuList(skuList);
            appletPickingProductResponses.add(response);
        }
        return CommonPage.copyPageInfo(page, appletPickingProductResponses);
    }

    @Override
    public List<StoreCartResponse> getPickingCart(Integer pickingId, Integer merId) {
        Integer uid = userService.getUserId();
        List<StoreCartResponse> list = new ArrayList<>();
        if(uid > 0){
            ChannelPicking picking = this.getById(pickingId);
            if(picking == null || picking.getIsDel() == 1){
                return list;
            }
            LambdaQueryWrapper<StoreCart> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(StoreCart::getUid, uid);
            queryWrapper.eq(StoreCart::getPickingId,pickingId);
            List<StoreCart> carts = storeCartService.list(queryWrapper);
            if(CollectionUtils.isEmpty(carts)) {
                return list;
            }
            List<String> skuIdList = carts.stream().map(StoreCart::getProductAttrUnique).collect(Collectors.toList());
            List<StoreProductPicking> productPickingList = storeProductPickingService.list(Wrappers.<StoreProductPicking>lambdaQuery().in(StoreProductPicking::getSkuId, skuIdList));
            List<String> exitSkuList = productPickingList.stream().map(StoreProductPicking::getSkuId).collect(Collectors.toList());

            List<Integer> enableCategoryMatchIds = categoryMatchService.getCategoryMatchIds(merId);
            List<Integer> ids = carts.stream().map(StoreCart::getProductId).collect(Collectors.toList());
            // 商品数据
            List<StoreProduct> products = storeProductService.list(Wrappers.<StoreProduct>lambdaQuery()
                    .in(StoreProduct :: getId, ids)
            );
            Map<Integer, StoreProduct> productMap = products.stream().collect(Collectors.toMap(StoreProduct::getId, Function.identity(), (key1, key2) -> key2));
            // 商户自定义商品数据
            List<StoreProductMer> storeProductMers = storeProductMerService.list(Wrappers.<StoreProductMer>lambdaQuery()
                    .in(StoreProductMer :: getProductId, ids)
            );
            Map<Integer, StoreProductMer> storeProductMerMap = storeProductMers.stream().collect(Collectors.toMap(StoreProductMer::getProductId, Function.identity(), (key1, key2) -> key2));
            carts.forEach(c -> {
                StoreProduct p = productMap.get(c.getProductId());
                if(null != p){
                    StoreProductMer spm = storeProductMerMap.get(p.getId());
                    // 商户自定义下架状态
                    boolean isMerShow = true;
                    if(null != spm && "1".equals(spm.getIsNotShow())) {
                        isMerShow = false;
                    }
                    //分类未启用时设置商品状态为失效
                    boolean enableCategoryBool = !enableCategoryMatchIds.contains(p.getCateId());
                    if(c.getStatus()){
                        if(p.getStock() < 1 || !p.getIsShow() || !isMerShow || enableCategoryBool || !exitSkuList.contains(c.getProductAttrUnique())){
                            c.setStatus(false);
                            storeCartService.updateById(c);
                        }
                    }else {
                        if(p.getStock() > 0 && p.getIsShow() && isMerShow && !enableCategoryBool && exitSkuList.contains(c.getProductAttrUnique())){
                            c.setStatus(true);
                            storeCartService.updateById(c);
                        }
                    }
                }else{
                    c.setStatus(false);
                    storeCartService.updateById(c);
                }
            });
            //带 StoreCart 类的多条件查询
            LambdaQueryWrapper<StoreCart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(StoreCart::getUid, uid);
            lambdaQueryWrapper.eq(StoreCart::getIsNew, 0);
            lambdaQueryWrapper.eq(StoreCart::getPickingId, pickingId);
            lambdaQueryWrapper.eq(StoreCart::getStatus, 1);
            lambdaQueryWrapper.orderByDesc(StoreCart::getCreateTime);
            List<StoreCart> storeCarts = storeCartService.list(lambdaQueryWrapper);
            if(CollectionUtils.isEmpty(storeCarts)){
                return list;
            }
            List<Integer> productIdList = storeCarts.stream().map(StoreCart::getProductId).distinct().collect(Collectors.toList());
            List<String> valueIdList = storeCarts.stream().map(StoreCart::getProductAttrUnique).distinct().collect(Collectors.toList());
            List<StoreProduct> productList = storeProductService.list(Wrappers.<StoreProduct>lambdaQuery().in(StoreProduct::getId, productIdList));
            Map<Integer, StoreProduct> storeProductMap = productList.stream().collect(Collectors.toMap(StoreProduct::getId, e -> e));
            List<StoreProductAttrValue> productAttrValueList = storeProductAttrValueDao.selectList(Wrappers.<StoreProductAttrValue>lambdaQuery()
                    .in(StoreProductAttrValue::getSourceSkuId, valueIdList)
                    .in(StoreProductAttrValue::getProductId,productIdList));
            Map<Integer, List<StoreProductAttrValue>> valueMap = productAttrValueList.stream().collect(Collectors.groupingBy(StoreProductAttrValue::getProductId));
            //批采价格
            List<StoreProductPicking> pickingList = storeProductPickingService.list(Wrappers.<StoreProductPicking>lambdaQuery().eq(StoreProductPicking::getPickingId, pickingId).in(StoreProductPicking::getSkuId, valueIdList));
            Map<String, StoreProductPicking> pickingMap = pickingList.stream().collect(Collectors.toMap(StoreProductPicking::getSkuId, e -> e, (v1, v2) -> v1));

            List<PickingProductResponse> responseList = new ArrayList<>();
            for (Map.Entry<Integer, List<StoreProductAttrValue>> entry : valueMap.entrySet()) {
                StoreProduct storeProduct = storeProductMap.get(entry.getKey());
                if(storeProduct == null){
                    continue;
                }
                List<StoreProductAttrValue> valueList = entry.getValue();
                List<PickingProductResponse> pickList = new ArrayList<>();
                for (StoreProductAttrValue value : valueList) {
                    PickingProductResponse response = new PickingProductResponse();
                    BeanUtils.copyProperties(storeProduct,response,"id");
                    response.setProductId(storeProduct.getId());
                    StoreProductPicking storeProductPicking = pickingMap.get(value.getSourceSkuId());
                    if(storeProductPicking == null){
                        continue;
                    }
                    response.setSkuId(value.getSourceSkuId());
                    response.setId(storeProductPicking.getId());
                    response.setCost(value.getCost());
                    response.setSuk(value.getSuk());
                    response.setStock(value.getStock());
                    response.setWholesalePrice(storeProductPicking.getPrice());
                    response.setPriceType(storeProductPicking.getPriceType());
                    pickList.add(response);
                }
                priceUtil.calcPickingProductWholesalePrice(pickList,merId,picking.getReceiptType());
                responseList.addAll(pickList);
            }
            Map<String, PickingProductResponse> responseMap = responseList.stream().collect(Collectors.toMap(PickingProductResponse::getSkuId, e -> e));
            List<StoreCartResponse> response = new ArrayList<>();
            for (StoreCart storeCart : storeCarts) {
                // 属性不存在证明失效
                StoreCartResponse storeCartResponse = new StoreCartResponse();
                BeanUtils.copyProperties(storeCart, storeCartResponse);
                StoreProduct product = storeProductMap.get(storeCart.getProductId());
                if (null == product){
                    continue;
                }
                StoreProductCartProductInfoResponse p = new StoreProductCartProductInfoResponse();
                BeanUtils.copyProperties(product, p);
                storeCartResponse.setProductInfo(p);
                storeCartResponse.setAttrStatus(false);
                PickingProductResponse productResponse = responseMap.get(storeCart.getProductAttrUnique());
                if(productResponse != null){
                    StoreProductAttrValue productAttrValue = new StoreProductAttrValue();
                    BeanUtils.copyProperties(productResponse, productAttrValue);
                    //productAttrValue.setId(productResponse.getSkuId());
                    // 主图覆盖
                    if(StringUtils.isBlank(productAttrValue.getImage())){
                        productAttrValue.setImage(p.getImage());
                    }
                    // 商品是否失效
                    if(StringUtils.isBlank(productAttrValue.getSuk())){
                        p.setAttrInfo(productAttrValue.setSuk("已失效"));
                    }else{
                        p.setAttrInfo(productAttrValue);
                    }
                    storeCartResponse.setAttrStatus(productAttrValue.getStock() > 0);
                    storeCartResponse.setTaxAndSecondPrice(productAttrValue.getTaxAndSecondPrice());
                    storeCartResponse.setTruePrice(productResponse.getWholesalePrice());
                    storeCartResponse.setTrueStock(productAttrValue.getStock());
                    storeCartResponse.setCostPrice(productResponse.getCost());
                    response.add(storeCartResponse);
                }
            }
            return response;
        }
        return list;
    }

    private void getProductConfig(PickingProductsRequest request) {
        ChannelMerchant channelMerchant = channelMerchantService.getChannelMerchantByMerId(request.getMerId());
        //可见配置
        List<Integer> brandIdsList = JSON.parseArray(channelMerchant.getBrandIds(), Integer.class);
        List<Integer> suppliersIdList = JSON.parseArray(channelMerchant.getSuppliersIds(), Integer.class);
        List<Integer> tempIdList = JSON.parseArray(channelMerchant.getTempId(), Integer.class);
        request.setVisibleBrandIds(brandIdsList);
        request.setVisibleTempIds(tempIdList);
        if (CollectionUtils.isNotEmpty(suppliersIdList)) {
            Supplier supplier = supplierService.getSupplierBarcode(request.getMerId());
            if (null != supplier) {
                suppliersIdList.add(supplier.getId());
            }
        }
        request.setVisibleSupplierIds(suppliersIdList);
        //不可见分类
        List<Integer> cateIdList = categoryMatchService.selectCategoryMatchDisable(request.getMerId()).stream().map(CategoryMatch::getId).collect(Collectors.toList());
        request.setInvisibleCateIds(cateIdList);
    }

    private void checkPicking(Integer merId) {
        ChannelMerchant channelMerchant = channelMerchantService.getChannelMerchantByMerId(merId);
        if (!Objects.equals(channelMerchant.getBatchPicking(), 1)) {
            throw new CrmebException("批采功能未开启");
        }
    }

}
